<script setup>
import { ref, computed, onMounted } from 'vue'
import { getCatagoriesList, getCatagoriesDishs } from '@/api/catagory'
import { addorder } from '@/api/order'
import { Plus, Minus, Search } from '@element-plus/icons-vue'
const categories = ref([])
const allDishes = ref({})
const currentCategory = ref(null)
const searchKeyword = ref('')
const cartItems = ref({})
const remark = ref('')

const currentDishes = computed(() => {
  if (!currentCategory.value) return []
  return allDishes.value[currentCategory.value.id] || []
})

const filteredDishes = computed(() => {
  if (!currentDishes.value) return []
  const filtered = currentDishes.value
  if (searchKeyword.value) {
    return filtered.filter((dish) =>
      dish.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }
  return filtered
})

const cartItemsList = computed(() => {
  return Object.entries(cartItems.value)
    .map(([id, quantity]) => {
      let dish = null
      Object.values(allDishes.value).some((dishes) => {
        dish = dishes.find((d) => d.id === parseInt(id))
        return dish !== undefined
      })
      return dish ? { ...dish, quantity } : null
    })
    .filter(Boolean)
})

const totalAmount = computed(() => {
  return cartItemsList.value.reduce((total, item) => {
    return total + item.price * item.quantity
  }, 0)
})

// Methods
const fetchCategories = async () => {
  try {
    const response = await getCatagoriesList()
    categories.value = response.data
    if (categories.value.length > 0) {
      currentCategory.value = categories.value[0]
      await fetchDishesByCategory(currentCategory.value.id)
    }
  } catch (error) {
    console.error('Failed to fetch categories:', error)
    ElMessage.error('获取分类失败')
  }
}

const fetchDishesByCategory = async (categoryId) => {
  if (allDishes.value[categoryId]) return

  try {
    const response = await getCatagoriesDishs(categoryId)
    allDishes.value = {
      ...allDishes.value,
      [categoryId]: response.data
    }
  } catch (error) {
    console.error('Failed to fetch dishes:', error)
    ElMessage.error('获取菜品失败')
  }
}

const handleCategoryClick = async (category) => {
  currentCategory.value = category
  await fetchDishesByCategory(category.id)
}

const increaseQuantity = (dish) => {
  cartItems.value[dish.id] = (cartItems.value[dish.id] || 0) + 1
}

const decreaseQuantity = (dish) => {
  if (cartItems.value[dish.id] > 0) {
    cartItems.value[dish.id]--
    if (cartItems.value[dish.id] === 0) {
      delete cartItems.value[dish.id]
    }
  }
}

const clearCart = () => {
  cartItems.value = {}
  remark.value = ''
}

const handleSubmitOrder = async () => {
  if (!Object.keys(cartItems.value).length) {
    ElMessage.warning('请先添加商品到购物车')
    return
  }

  try {
    const orderData = {
      orderDetails: cartItemsList.value.map((item) => ({
        dishId: item.id,
        name: item.name,
        number: item.quantity,
        amount: item.price * item.quantity
      })),
      remark: remark.value,
      amount: totalAmount.value
    }

    await addorder(orderData)
    ElMessage.success('订单提交成功')
    clearCart()
  } catch (error) {
    console.error('Failed to submit order:', error)
    ElMessage.error('订单提交失败')
  }
}

// Lifecycle hooks
onMounted(() => {
  fetchCategories()
})
</script>

<template>
  <div class="order-page">
    <!-- Category Sidebar -->
    <div class="category-sidebar">
      <div class="category-header">
        <h2>菜品分类</h2>
      </div>
      <div class="category-list">
        <div
          v-for="category in categories"
          :key="category.id"
          class="category-item"
          :class="{ active: currentCategory?.id === category.id }"
          @click="handleCategoryClick(category)"
        >
          {{ category.name }}
        </div>
      </div>
    </div>

    <!-- Main Content -->
    <div class="dish-content">
      <div class="dish-header">
        <h2>{{ currentCategory?.name || '所有菜品' }}</h2>
        <div class="dish-search">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索菜品"
            clearable
            :prefix-icon="Search"
          />
        </div>
      </div>

      <div class="dish-list">
        <el-card
          v-for="dish in filteredDishes"
          :key="dish.id"
          class="dish-card"
          :body-style="{ padding: '0' }"
        >
          <div class="dish-info">
            <img :src="dish.image" :alt="dish.name" class="dish-image" />
            <div class="dish-details">
              <h3>{{ dish.name }}</h3>
              <p class="description">{{ dish.description || '暂无描述' }}</p>
              <div class="price">¥{{ dish.price.toFixed(2) }}</div>
            </div>
            <div class="dish-actions">
              <el-button
                type="primary"
                circle
                size="small"
                :icon="Minus"
                @click="decreaseQuantity(dish)"
                :disabled="!cartItems[dish.id]"
              />
              <span class="quantity">{{ cartItems[dish.id] || 0 }}</span>
              <el-button
                type="primary"
                circle
                size="small"
                :icon="Plus"
                @click="increaseQuantity(dish)"
              />
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- Cart Sidebar -->
    <div class="cart-sidebar">
      <div class="cart-header">
        <h2>购物车</h2>
        <el-button
          type="text"
          @click="clearCart"
          :disabled="!Object.keys(cartItems).length"
        >
          清空
        </el-button>
      </div>

      <div class="cart-items">
        <template v-if="cartItemsList.length">
          <div v-for="item in cartItemsList" :key="item.id" class="cart-item">
            <div class="item-info">
              <span class="item-name">{{ item.name }}</span>
              <span class="item-price"
                >¥{{ (item.price * item.quantity).toFixed(2) }}</span
              >
            </div>
            <div class="item-actions">
              <el-button
                type="primary"
                circle
                size="small"
                :icon="Minus"
                @click="decreaseQuantity(item)"
              />
              <span class="quantity">{{ item.quantity }}</span>
              <el-button
                type="primary"
                circle
                size="small"
                :icon="Plus"
                @click="increaseQuantity(item)"
              />
            </div>
          </div>
        </template>
        <div v-else class="empty-cart">购物车是空的</div>
      </div>

      <div class="cart-footer">
        <div class="cart-total">
          <span>合计:</span>
          <span class="total-price">¥{{ totalAmount.toFixed(2) }}</span>
        </div>
        <el-input
          v-model="remark"
          type="textarea"
          rows="2"
          placeholder="请输入备注信息"
          class="remark-input"
        />
        <el-button
          type="primary"
          class="submit-btn"
          :disabled="!cartItemsList.length"
          @click="handleSubmitOrder"
        >
          提交订单
        </el-button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.order-page {
  display: flex;
  height: 88vh;
  background-color: #f5f5f5;
}

.category-sidebar {
  width: 200px;
  background-color: #fff;
  border-right: 1px solid #e8e8e8;
  display: flex;
  flex-direction: column;
}

.category-header {
  padding: 20px;
  border-bottom: 1px solid #e8e8e8;
}

.category-header h2 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.category-list {
  flex: 1;
  overflow-y: auto;
}

.category-item {
  padding: 15px 20px;
  cursor: pointer;
  transition: all 0.3s;
}

.category-item:hover {
  background-color: #f5f5f5;
  color: var(--el-color-primary);
}

.category-item.active {
  background-color: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
  border-right: 3px solid var(--el-color-primary);
}

.dish-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #fff;
}

.dish-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.dish-search {
  width: 300px;
}

.dish-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.dish-card {
  transition: transform 0.3s;
}

.dish-card:hover {
  transform: translateY(-4px);
}

.dish-info {
  display: flex;
  flex-direction: column;
}

.dish-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.dish-details {
  padding: 15px;
}

.description {
  color: #666;
  font-size: 14px;
  margin: 8px 0;
}

.price {
  color: var(--el-color-danger);
  font-size: 18px;
  font-weight: bold;
}

.dish-actions {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 0 15px 15px;
  gap: 10px;
}

.cart-sidebar {
  width: 300px;
  background-color: #fff;
  border-left: 1px solid #e8e8e8;
  display: flex;
  flex-direction: column;
}

.cart-header {
  padding: 20px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.cart-items {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.empty-cart {
  text-align: center;
  color: #999;
  padding: 40px 0;
}

.cart-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.item-info {
  flex: 1;
}

.item-name {
  display: block;
  margin-bottom: 4px;
}

.item-price {
  color: var(--el-color-danger);
}

.cart-footer {
  padding: 20px;
  border-top: 1px solid #e8e8e8;
}

.cart-total {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.total-price {
  color: var(--el-color-danger);
  font-size: 20px;
  font-weight: bold;
}

.remark-input {
  margin-bottom: 15px;
}

.submit-btn {
  width: 100%;
}

.quantity {
  min-width: 30px;
  text-align: center;
}

@media (max-width: 1200px) {
  .category-sidebar {
    width: 180px;
  }

  .cart-sidebar {
    width: 280px;
  }

  .dish-search {
    width: 250px;
  }
}

@media (max-width: 992px) {
  .dish-list {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  }
}
</style>
